package com.cxj.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cxj.musicplayer.MainActivity;
import com.cxj.musicplayer.R;
import com.cxj.musicplayer.adapter.PlayListAdapter;
import com.cxj.musicplayer.audio.PlayerManager;
import com.cxj.musicplayer.bean.Song;
import com.cxj.musicplayer.component.RoundImageView;
import com.cxj.musicplayer.dao.SongDBUtil;
import com.cxj.musicplayer.data.ActivityManager;
import com.cxj.musicplayer.data.DataManager;
import com.cxj.musicplayer.musicsource.network.DownloadFrom163;
import com.cxj.musicplayer.service.MediaService;
import com.cxj.musicplayer.utils.FileUtil;
import com.cxj.musicplayer.utils.SqliteUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class OnPlaying extends Activity {

    public SeekBar sb;
    public Button btn;
    public TextView pass_time;
    public TextView all_time;
    public RoundImageView imageView;
    public TextView song_name;
    public ImageView back;
    public TextView author_name;
    public String song_id;
    public int song_i;
    public Button is_love;
    public Song data_song;
    private boolean locker = true;

    private MediaService.MusicController musicController;


    public final int UPDATE_SEEKBAR = 2;
    public final int UPDATE_PASS_TIME = 3;
    public final int UPDATE_ALL_TIME = 4;
    public final int UPDATE_BTN_STATE = 5;
    public final int UPDATE_IMG_STATE = 6;
    public final int DOWNLOAD_FAIL = 7;

    public boolean isSeekBarChanging = false;

    @SuppressLint("HandlerLeak")
    public Handler handle = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE_SEEKBAR:
                    sb.setProgress(msg.getData().getInt("d"));
                    break;
                case UPDATE_PASS_TIME:
                    pass_time.setText(msg.getData().getString("pass_time"));
                    break;
                case UPDATE_ALL_TIME:
                    all_time.setText(msg.getData().getString("all_time"));
                    break;
                case UPDATE_BTN_STATE:
                    String res = msg.getData().getString("playState");
                    if("playing".equals(res)){
                        imageView.start_animation();
                        btn.setText("暂停");
                    }else{
                        imageView.clear_animation();
                        btn.setText("播放");
                    }
                    break;

                case DOWNLOAD_FAIL:
                    Toast.makeText(OnPlaying.this, "歌曲下载失败， 无法播放", Toast.LENGTH_SHORT).show();
                    break;
                    default:
                        break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_on_playing);

        String source = getIntent().getStringExtra("song_source");

        musicController = (MediaService.MusicController) DataManager.concurrentHashMap_object_data.get("music_controller");

        String from = getIntent().getStringExtra("from");
        if(!"reload".equals(from))
            musicController.finish();

        ActivityManager.activities.put(getClass(), this);

        Log.i(getClass().getName(), "启动");

        song_id = getIntent().getStringExtra("song_id");
        song_i = getIntent().getIntExtra("song_i", -1);

        sb = findViewById(R.id.sb1);
        pass_time = findViewById(R.id.pass_time);
        all_time = findViewById(R.id.all_time);
        btn = findViewById(R.id.btn);
        imageView = findViewById(R.id.song_pic);
        back = findViewById(R.id.back);
        song_name = findViewById(R.id.song_name);
        author_name = findViewById(R.id.author_name);
        is_love = findViewById(R.id.is_love);


        SongDBUtil songDBUtil = new SongDBUtil(getBaseContext(), "music_db", null, 1);
        data_song = songDBUtil.querySong(song_id);
        if(null != data_song){
            String l = data_song.getLove();
            if("yes".equals(l)){
                is_love.setText("已加入喜欢");
            }
            songDBUtil.close();
        }

        is_love.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if(!locker)
                    return;
                locker = false;
                String t = is_love.getText().toString();
                SongDBUtil songDBUtil = new SongDBUtil(getBaseContext(), "music_db", null, 1);
                if("加入喜欢".equals(t)){
                    if(data_song == null){
                        Song now_song = musicController.getSongInfo();
                        if(now_song == null)
                            return;
                        now_song.setLove("yes");
                        songDBUtil.insertSong(now_song);

                    }else{
                        data_song.setLove("yes");
                        songDBUtil.updateSong(data_song);
                    }
                    is_love.setText("已加入喜欢");
                }else{
                    if(data_song == null){
                        Song now_song = musicController.getSongInfo();
                        if(now_song == null)
                            return;
                        now_song.setLove("no");
                        songDBUtil.insertSong(now_song);

                    }else{
                        data_song.setLove("no");
                        songDBUtil.updateSong(data_song);
                    }
                    is_love.setText("加入喜欢");
                }
                songDBUtil.close();
                locker = true;
            }
        });


        back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                OnPlaying.this.finish();
            }
        });

        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                MediaService.MusicController controller = (MediaService.MusicController)DataManager.concurrentHashMap_object_data.get("music_controller");
                if("playing".equals(controller.getPlayState())){
                    controller.pause();
                    btn.setText("播放");
                    imageView.clear_animation();
                }else if("pause".equals(controller.getPlayState())){
                    controller.replay(OnPlaying.this);
                    btn.setText("暂停");
                    imageView.start_animation();
                }
            }
        });


        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = false;
                ((MediaService.MusicController)DataManager.concurrentHashMap_object_data.get("music_controller")).setPosition(seekBar.getProgress());
            }
        });

        Bitmap bitmap = FileUtil.get_pic_from_local(this, song_id);
        if(bitmap != null){
            imageView.setImageBitmap(bitmap);
        }else {

            String path = getApplicationContext().getFilesDir().getAbsolutePath() + "/song_pic/";
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            try {
                DownloadFrom163.download_pic(DownloadFrom163.get_song_pic_by_id(song_id), path + song_id + ".jpg");
            } catch (IOException e) {
                e.printStackTrace();
                File p = new File(path + "/song_pic/" + song_id + ".jpg");
                if(p.exists()){
                    p.delete();
                }
            }
            bitmap = FileUtil.get_pic_from_local(this, song_id);
            if(bitmap != null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(R.drawable.ic_launcher_background);
        }

        song_name.setText(DataManager.array_data.get(source + "song_name")[song_i]);
        author_name.setText(DataManager.array_data.get(source + "author_name")[song_i]);


        if("reload".equals(from)){
            Log.i(getClass().getName(), "重载");
            PlayerManager.getPlayerManager(this.getBaseContext()).reload_song(this, song_id, song_i);
        }else{
            Log.i(getClass().getName(), "播放");
            PlayerManager.getPlayerManager(this.getBaseContext()).play_songs(this, song_id, song_i, source);
        }

    }

    @Override
    protected void onDestroy() {
        ActivityManager.activities.remove(getClass());
        super.onDestroy();
    }
}
